package com.dycn.exception;



import com.dycn.util.AppResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
     @ExceptionHandler(value = Exception.class)
     @ResponseBody
     public AppResultData<String> globalError(HttpServletRequest req, Exception e){
         if(e instanceof GlobalException){
          GlobalException globalException= (GlobalException) e;
          //Authentication failed for token submission [org.apache.shiro.authc.UsernamePasswordToken - 13611111111, rememberMe=false].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).
          return globalException.getAppResultData();
      }
     else if(e instanceof BindException){
          BindException bindException= (BindException) e;
          List<ObjectError> errors=bindException.getAllErrors();
          ObjectError objectError=errors.get(0);
          return  AppResultData.error(objectError.getDefaultMessage(),"");

      }else if(e instanceof AuthenticationException){
             e.printStackTrace();
             return  AppResultData.error("用户名或者密码错误",e.toString());
         }else {
          e.printStackTrace();

          return  AppResultData.error("系统错误",e.toString());
      }
     }
}
